import { login, info } from "@/api/user";
import {
  getToken,
  setToken,
  clearToken,
  getUser,
  setUser,
  clearUser,
} from "@/utils";
const getDefaultState = () => {
  return {
    token: getToken() || "",
    userInfo: getUser() || undefined,
  };
};

const state = getDefaultState();

const mutations = {
  // reset state
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
    clearUser();
    clearToken();
  },
  // set token
  SET_TOKEN: (state, token) => {
    state.token = token;
    setToken(token);
  },
  // set user
  SET_USER: (state, userInfo) => {
    state.userInfo = userInfo;
    setUser(userInfo);
  },
};

const actions = {
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response) => {
          if (response.code === 200) {
            const { data } = response;
            commit("SET_TOKEN", data);
            info().then((res) => {
              if (res.code === 200) {
                commit("SET_USER", res.data);
                resolve(res);
              } else {
                reject(res);
              }
            });
          } else {
            reject(response);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  logout({ commit }) {
    return new Promise((resolve) => {
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
